package com.sitc.administrator.application.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.BottomNavigationBar.OnTabSelectedListener;
import com.ashokvarma.bottomnavigation.TextBadgeItem;
import com.sitc.administrator.application.AppContext;
import com.sitc.administrator.application.R;
import com.sitc.administrator.application.adapter.MainContentAdapter;
import com.sitc.administrator.application.datasource.SharedPreferencesUtil;
import com.sitc.administrator.application.domain.User;
import com.sitc.administrator.application.domain.event.MessageArrivedEvent;
import com.sitc.administrator.application.mqtt.MqttManager;
import com.sitc.administrator.application.view.BadgeView;
import com.sitc.zxing.android.CaptureActivity;
import com.sitc.zxing.common.Constant;
import com.xz.badgeview.QBadgeView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


import butterknife.OnClick;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.sitc.administrator.application.util.IsUrl.isHttpUrl;
import static com.sitc.administrator.application.util.ToastUtil.showSortToast;


public class MainActivity extends BaseCommonActivity {

    public static final String TAG = MainActivity.class.getSimpleName();

    private static final int HomePage = 100;
    private static final int REQUEST_CODE_SCAN = 0;
    private DrawerLayout drawer_layout;
    protected Toolbar toolbar;
    private ViewPager vp;
    MainContentAdapter adapter;
    private PopupWindow popupwindow;
    private View tipContentView;
    private ImageView tipshowImage;
    BottomNavigationBar bottom_navigationbar;
    private LinearLayout company_info;
    private LinearLayout company_web;
    private LinearLayout public_card;
    private TextView tv_nickname;
    private TextView tv_description;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        onTheme();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }

    @Override
    protected void initViews() {



        //head ------>
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.homeItem));
        setSupportActionBar(toolbar);

        //content ------>
        vp = findViewById(R.id.vp_content);
        adapter = new MainContentAdapter(getActivity(), getSupportFragmentManager());
        vp.setAdapter(adapter);

        ArrayList<Integer> datas = new ArrayList<>();
        datas.add(1);
        datas.add(2);
        datas.add(3);
        adapter.setDatas(datas);

        //缓存三个页面
        vp.setOffscreenPageLimit(3);
        vp.setCurrentItem(0);


        //drawer ------>
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer_layout.addDrawerListener(toggle);
        toggle.syncState();


        company_info = findViewById(R.id.company_info);
        company_web = findViewById(R.id.company_web);
        public_card = findViewById(R.id.public_card);

//        QBadgeView qBadgeView = new QBadgeView(this);
//        qBadgeView.bindTarget(public_card).setBadgeNumber(12);
//
//        qBadgeView.setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
//            @Override
//            public void onDragStateChanged(int i, Badge badge, View view) {
//
//            }
//        });


        BadgeView badgeView = new BadgeView(this);
        badgeView.setTargetView(public_card);
        badgeView.setBadgeCount(100);


        //bottom_navigationbar ------>
        bottom_navigationbar = findViewById(R.id.bottom_navigation_bar) ;
        InitNavigationBar();


        //popupwindow ------>
        tipshowImage = findViewById(R.id.tip_image) ;
        tipContentView = LayoutInflater.from(this).inflate(R.layout.popupwindow,null);
        popupwindow = new PopupWindow(tipContentView,LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT,true);
        popupwindow.setBackgroundDrawable(new ColorDrawable(0xFFF4E9E8));
        tipContentView.setOnClickListener(this);

        tv_nickname = findViewById(R.id.tv_nickname) ;
        tv_description = findViewById(R.id.tv_description) ;



    }

    private void InitNavigationBar() {

        bottom_navigationbar.setMode(BottomNavigationBar.MODE_FIXED);
        bottom_navigationbar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE);

        String value = sp.get("__AppTheme");
        int id;
        if(value.equals("1")){
            id = R.color.main_color_1;
        }else if(value.equals("2")){
            id = R.color.main_color_2;
        }else if(value.equals("3")){
            id = R.color.main_color_3;
        }else if(value.equals("4")){
            id = R.color.main_color_4;
        }else {
            id = R.color.main_color_1;
        }


//        BadgeItem badgeItem = new BadgeItem()
//                .setBorderWidth(4)
//                .setAnimationDuration(200)
//                .setBackgroundColorResource(R.color.red)
//                .setHideOnSelect(false)
//                .setText("0");


        BadgeView badgeView = new BadgeView(this);
        badgeView.setBadgeCount(100);

        TextBadgeItem text =new TextBadgeItem();
        text.setText("1");

        List<BottomNavigationItem> items = new ArrayList<>();
        items.add(new BottomNavigationItem(R.drawable.home, R.string.homeItem).setActiveColorResource(R.color.white));
        items.add(new BottomNavigationItem(R.drawable.msg, R.string.msgItem)
                .setBadgeItem(text)
                .setActiveColorResource(R.color.white));
        items.add(new BottomNavigationItem(R.drawable.me, R.string.meItem).setActiveColorResource(R.color.white));

        for (BottomNavigationItem item : items) {
            bottom_navigationbar.addItem(item);
        }

        bottom_navigationbar
                .setBarBackgroundColor(id)
                .initialise();
    }

    @Override
    protected void initListener() {

        bottom_navigationbar.setTabSelectedListener(new OnTabSelectedListener(){

            @Override
            public void onTabSelected(int position) {
                if (position>=0 && position<3){
                    vp.setCurrentItem(position);
                    if(position==0){toolbar.setTitle(getResources().getString(R.string.homeItem));}
                    else if(position==1){toolbar.setTitle(getResources().getString(R.string.msgItem));}
                    else if(position==2){toolbar.setTitle(getResources().getString(R.string.meItem));}
                }
            }
            @Override
            public void onTabUnselected(int position) {}

            @Override
            public void onTabReselected(int position) {}

        });
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
            @Override
            public void onPageScrolled(int i, float v, int i1) {}

            @Override
            public void onPageSelected(int i) {
                bottom_navigationbar.selectTab(i);
                if(i==0){toolbar.setTitle(getResources().getString(R.string.homeItem));}
                else if(i==1){toolbar.setTitle(getResources().getString(R.string.msgItem));}
                else if(i==2){toolbar.setTitle(getResources().getString(R.string.meItem));}
            }
            @Override
            public void onPageScrollStateChanged(int i) {}

        });


        company_info.setOnClickListener(this);
        company_web.setOnClickListener(this);
        public_card.setOnClickListener(this);
        this.findViewById(R.id._settings).setOnClickListener(this);
        this.findViewById(R.id._app_exit).setOnClickListener(this);

        tipshowImage.setOnClickListener(this);
        tipContentView.findViewById(R.id.tip_company_info).setOnClickListener(this);
        tipContentView.findViewById(R.id.tip_company_web).setOnClickListener(this);
        tipContentView.findViewById(R.id.tip_public_card).setOnClickListener(this);
        tipContentView.findViewById(R.id.tip_scan).setOnClickListener(this);





    }


    @Override
    protected void initDatas() {

        User user = new User();
        user.setNickname(TextUtils.isEmpty(sp.getUserName())? "":sp.getUserName());
        user.setDescription(TextUtils.isEmpty(sp.getDescription())? "":sp.getDescription());
        showUserInfo(user);
    }

    @Override
    protected void initComplete(){

        EventBus.getDefault().register(this);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            //可以处理应用退出
            //super.onBackPressed();
        }
    }

    private void closeDrawer() {
        drawer_layout.closeDrawer(Gravity.START);
    }

    public void showTipWindow(){

        popupwindow.showAsDropDown(tipshowImage,0,70);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.tip_image:

                showTipWindow();
                break;

            case R.id.tip_scan:
                //showSortToast(this,"后面再来实现该功能");
                //do...
                Intent intent = new Intent(MainActivity.this,CaptureActivity.class);
                startActivityForResult(intent,REQUEST_CODE_SCAN);


                popupwindow.dismiss();
                break;
            case R.id.tip_company_info:

                //"http://www.baidu.com"
                startWebView(getResources().getString(R.string.company_info),
                        "file:///android_asset/apps/webapp/web/playVideo.html",null);

                popupwindow.dismiss();
                break;
            case R.id.company_info:

                startWebView(getResources().getString(R.string.company_info),
                        "file:///android_asset/apps/webapp/web/company.html",null);

                popupwindow.dismiss();
                break;
            case R.id.tip_company_web:
            case R.id.company_web:
                startWebView(getResources().getString(R.string.company_web),
                        "http://www.sitcsys.com",null);

                popupwindow.dismiss();
                break;

            case R.id.tip_public_card:
            case R.id.public_card:

                startWebView(getResources().getString(R.string.public_card),
                        "file:///android_asset/apps/webapp/web/card.html",null);

                popupwindow.dismiss();
                break;

            case R.id._settings:

                doTest();
                //startActivity(SDK_WebView.class);
                //startActivity(SettingsActivity.class);
                break;

            case R.id._app_exit:
                AppContext app = (AppContext)getApplication();
                app.exitApp();
                break;

            default:
                //如果当前界面没有处理，就调用父类的方法
                super.onClick(v);
                break;
        }

    }

    private void doTest() {

//        params.put("username", sp.getUserName());
//        params.put("token", sp.getToken());
//        String args = gs.toJson(params);
//
//        startWebView("Test",
//                "file:///android_asset/apps/webapp/web/dclList.html",args);

//        startActivity(baiduMapActivity.class);


//        String host = "tcp://120.27.140.246:61613";
//        String username = "lys";
//        String password = "password";
//
//        MqttManager mqttManager = new MqttManager(host,username,password,"sitcReal/#");
//        mqttManager.start();
//        mqttManager.checkNet();




    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                showSortToast(this,content);

                if(isHttpUrl(content)){

                    startWebView("链接",content,null);

                }else{
                    Log.d("onActivityResult", content);
                }

            }
        }

    }



    public void showUserInfo(User user){

        tv_nickname.setText(user.getNickname());
        tv_description.setText(user.getDescription());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageArrived(MessageArrivedEvent event) {

        Log.i(TAG,"received topic : " + event.getTopic());
        Log.i(TAG,"received msg : " + event.getPlayload());

    }




    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


}

